<?php

namespace CHOMP\SGIBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CHOMP\SGIBundle\Entity\GrupoSoporte;
use CHOMP\SGIBundle\Form\GrupoSoporteType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use CHOMP\SGIBundle\Services\SessionManager;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * GrupoSoporte controller.
 *
 * @Route("/gruposoporte")
 */
class GrupoSoporteController extends Controller
{
	/**
	 * 
	 * @var SessionManager
	 * @DI\Inject("session.manager")
	 */
	public $sessionSvc;

   	public function listarAction(Request $request, $page)
	{
		if ($this->sessionSvc->userIsLogged()){
			$us = $this->sessionSvc->getCurrentUser();
			if($us->getRol()->getNombre()=='Administrador'){
	
				$workflows = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Workflow')->getByEmmpresa($this->sessionSvc->getSession('empresa'));
				$cuentaAnalitica = $this->getDoctrine()->getRepository('CHOMPSGIBundle:CuentaAnalitica')->getByEmmpresa($this->sessionSvc->getSession('empresa'));
				$grupoSoporte = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->getByEmmpresa($this->sessionSvc->getSession('empresa'));
				
				if(count($grupoSoporte)<1){
					$this->sessionSvc->addFlash('msgWarn','Bienvenido! Debe dar de alta al menos un Grupo de Soporte.');				
					return $this->redirect($this->generateUrl('gruposoporte_nuevo'));
				}
				if(count($cuentaAnalitica)<1){
					$this->sessionSvc->addFlash('msgWarn','Bienvenido! Debe dar de alta al menos una Cuenta Analitica.');				
					return $this->redirect($this->generateUrl('cuentaAnalitica_nuevo'));
				}
				if(count($workflows)<1){
					$this->sessionSvc->addFlash('msgWarn','Bienvenido! Debe dar de alta al menos un Workflow.');				
					return $this->redirect($this->generateUrl('workflow_nuevo'));			
				}
			}		
			$session = $request->getSession();
			if($session->get('esAdmin')=='NO'){
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->getAllActivasPorEmpresa($session->get('empresa'));
			}else{
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->getAllActivas();		
			}		
		
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			return $this->render('CHOMPSGIBundle:GrupoSoporte:listar.html.twig', array('grupoSoportes' => $paginador));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}	

    /**
     * Creates a new GrupoSoporte entity.
     *
     * @Route("/", name="gruposoporte_create")
     * @Method("POST")
     * @Template("CHOMPSGIBundle:GrupoSoporte:nuevo.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new GrupoSoporte();
		$session = $request->getSession();
		$empresa = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->find($session->get('empresa'));
		$form = $this->createCreateForm($entity, $session->get('empresa'), $session->get('esAdmin'));
        $form->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity->setEmpresa($empresa);
			$em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('gruposoporte_ver', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a GrupoSoporte entity.
    *
    * @param GrupoSoporte $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(GrupoSoporte $entity, $idEmpresa, $esAdmin)
    {
		$form = $this->createForm(new GrupoSoporteType($idEmpresa, $esAdmin), $entity, array(
            'action' => $this->generateUrl('gruposoporte_create'),
            'method' => 'POST',
        ));
		$form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }

    /**
     * Displays a form to create a new GrupoSoporte entity.
     *
     * @Route("/nuevo", name="gruposoporte_nuevo")
     * @Method("GET")
     * @Template()
     */
    public function nuevoAction(Request $request)
    {
		if ($this->sessionSvc->userIsLogged()){
			$session = $request->getSession();
			$entity = new GrupoSoporte();
			$entity->setBorrado(false);
			$form   = $this->createCreateForm($entity, $session->get('empresa'), $session->get('esAdmin'));
	
			return array(
				'entity' => $entity,
				'form'   => $form->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
     * Finds and displays a GrupoSoporte entity.
     *
     * @Route("/{id}", name="gruposoporte_ver")
     * @Method("GET")
     * @Template()
     */
    public function verAction($id)
    {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:GrupoSoporte')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find GrupoSoporte entity.');
			}
	
			return array(
				'entity'      => $entity,
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
     * Displays a form to edit an existing GrupoSoporte entity.
     *
     * @Route("/{id}/editar", name="gruposoporte_editar")
     * @Method("GET")
     * @Template()
     */
    public function editarAction(Request $request, $id)
    {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
			$session = $request->getSession();
			$entity = $em->getRepository('CHOMPSGIBundle:GrupoSoporte')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find GrupoSoporte entity.');
			}
	
			$editForm = $this->createEditForm($entity, $session->get('empresa'), $session->get('esAdmin'));
			
			return array(
				'entity'      => $entity,
				'edit_form'   => $editForm->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
    * Creates a form to edit a GrupoSoporte entity.
    *
    * @param GrupoSoporte $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(GrupoSoporte $entity, $idEmpresa, $esAdmin)
    {
        $form = $this->createForm(new GrupoSoporteType($idEmpresa, $esAdmin), $entity, array(
            'action' => $this->generateUrl('gruposoporte_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }
    /**
     * Edits an existing GrupoSoporte entity.
     *
     * @Route("/{id}", name="gruposoporte_update")
     * @Method("PUT")
     * @Template("CHOMPSGIBundle:GrupoSoporte:editar.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
		$session = $request->getSession();
        $entity = $em->getRepository('CHOMPSGIBundle:GrupoSoporte')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find GrupoSoporte entity.');
        }

        $editForm = $this->createEditForm($entity, $session->get('empresa'), $session->get('esAdmin'));
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('gruposoporte_ver', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        );
    }
    /**
     * Deletes a GrupoSoporte entity.
     *
     * @Route("/{id}", name="gruposoporte_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('CHOMPSGIBundle:GrupoSoporte')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find GrupoSoporte entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('gruposoporte'));
    }

    /**
     * Creates a form to delete a GrupoSoporte entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('gruposoporte_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Borrar'))
            ->getForm()
        ;
    }

	public function borrarAction($id)
	{
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
			$idsArray = explode (',', $id);
	
			for ($i = 0; $i < count($idsArray); $i++){
				$gpABorrar = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->find($idsArray[$i]);
				$gpABorrar->setBorrado(1);
				$em->persist($gpABorrar);
			}
	
			$em->flush();
					
			return $this->redirect($this->generateUrl('gruposoporte_listar'));	
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}

    public function datePickerAction()
    {
        return $this->render('CHOMPSGIBundle:GrupoSoporte:testDatePicker.html.twig');
    }
        
	public function filtrarAction(Request $request, $page)
	{
		if ($this->sessionSvc->userIsLogged()){
			$nombre = $request->get('nombreGrupo');
			if($this->sessionSvc->getSession('esAdmin') == 'SI'){
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->getFiltradoAdmin($nombre);
			}else{
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->getFiltrado($nombre, $this->sessionSvc->getSession('empresa'));			
			}
			
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			return $this->render('CHOMPSGIBundle:GrupoSoporte:listar.html.twig', array('grupoSoportes' => $paginador));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}	

}
